package org.citra.citra_emu.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * 时间格式工具类
 *
 * @author jie.li
 */
public class TimeUtil {
    private static ThreadLocal<SimpleDateFormat> DateLocal = new ThreadLocal();

    /**
     * 返回固定格式的时间
     *
     * @param timeMills
     * @param formatType
     * @return
     */
    public static String getFormatTimeByTimeMillis(long timeMills,
                                                   String formatType) {
        Date date = new Date();
        date.setTime(timeMills);
        SimpleDateFormat formatter = new SimpleDateFormat(formatType,
                Locale.CHINESE);
        return formatter.format(date);
    }

    public static String GetDateFormat(String mServerData, boolean noCurrentYear, boolean noSecond) {
        if (StringUtil.isEmpty(mServerData)) {
            return null;
        }
        mServerData = mServerData.replace("/", "-");
        if (noCurrentYear) {
            Calendar calendar = Calendar.getInstance();  //获取当前时间，作为图标的名字
            String year = calendar.get(Calendar.YEAR) + "";
            mServerData = mServerData.replace(year + "-", "");
        }
        if (noSecond && mServerData.length() >= 3) {
            mServerData = mServerData.substring(0, mServerData.length() - 3);
        }
        return mServerData;
    }

    //返回日期的中文描述（今天、明天、后天、昨天）

    /**
     * 判断是否为昨天(效率比较高)
     *
     * @param day 传入的 时间  "2016-06-28 10:10:30" "2016-06-28" 都可以
     * @return true今天 false不是
     * @throws ParseException
     */
    public static String GetDateWithChinese(String day) {
        if (StringUtil.isEmpty(day)) {
            return null;
        }
        day = day.replace("/", "-");
        Calendar pre = Calendar.getInstance();//本地日历
        Date predate = new Date(System.currentTimeMillis());
        pre.setTime(predate);

        Calendar cal = Calendar.getInstance();//数据日历
        Date date = null;
        try {
            date = getDateFormat().parse(day);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (date != null) {
            cal.setTime(date);
            int diffDay = -1;
            int isSameYear = -1;

            if (cal.get(Calendar.YEAR) == (pre.get(Calendar.YEAR))) {
                diffDay = cal.get(Calendar.DAY_OF_YEAR)
                        - pre.get(Calendar.DAY_OF_YEAR);
                isSameYear = 0;
            }
            if (pre.get(Calendar.YEAR) - cal.get(Calendar.YEAR) == 1) {
                isSameYear = 1;
                if (isLeapYear(cal.get(Calendar.YEAR))) {
                    diffDay = -366 + cal.get(Calendar.DAY_OF_YEAR)
                            - pre.get(Calendar.DAY_OF_YEAR);
                } else {
                    diffDay = -365 + cal.get(Calendar.DAY_OF_YEAR)
                            - pre.get(Calendar.DAY_OF_YEAR);
                }
            }

            if (cal.get(Calendar.YEAR) - pre.get(Calendar.YEAR) == 1) {
                isSameYear = 2;
                if (isLeapYear(cal.get(Calendar.YEAR))) {
                    diffDay = cal.get(Calendar.DAY_OF_YEAR) + 366
                            - pre.get(Calendar.DAY_OF_YEAR);
                } else {
                    diffDay = cal.get(Calendar.DAY_OF_YEAR) + 365
                            - pre.get(Calendar.DAY_OF_YEAR);
                }
            }

            if (isSameYear != -1) {
                if (diffDay >= 0 && diffDay <= 30) {//今天或者以后一个月以内
                    String minute = cal.get(Calendar.MINUTE) < 10 ? "0" + cal.get(Calendar.MINUTE) : cal.get(Calendar.MINUTE) + "";
                    switch (diffDay) {
                        case 0://今天
                            day = "今天 " + cal.get(Calendar.HOUR_OF_DAY) + ":" + minute;
                            break;
                        case 1://明天
                            day = "明天 " + cal.get(Calendar.HOUR_OF_DAY) + ":" + minute;
                            break;
                        case 2://后天
                            day = "后天 " + cal.get(Calendar.HOUR_OF_DAY) + ":" + minute;
                            break;
                        default://以后一个月以内
                            day = diffDay + "天后";
                            break;
                    }
                } else if (diffDay < 0 && diffDay >= -30) {//以前一个月以内
                    String minute = cal.get(Calendar.MINUTE) < 10 ? "0" + cal.get(Calendar.MINUTE) : cal.get(Calendar.MINUTE) + "";
                    switch (diffDay) {
                        case -1://昨天
                            day = "昨天 " + cal.get(Calendar.HOUR_OF_DAY) + ":" + minute;
                            break;
                        case -2://前天
                            day = "前天 " + cal.get(Calendar.HOUR_OF_DAY) + ":" + minute;
                            break;
                        default://以前一个月以内
                            day = Math.abs(diffDay) + "天前";
                            break;
                    }
                } else {//以后或者以前一个月以上
                    int diffMonth = 0;
                    if (isSameYear == 0) {
                        diffMonth = cal.get(Calendar.MONTH) - pre.get(Calendar.MONTH);
                    } else if (isSameYear == 1) {
                        diffMonth = -(pre.get(Calendar.MONTH) + (12 - cal.get(Calendar.MONTH)));
                    } else if (isSameYear == 2) {
                        diffMonth = pre.get(Calendar.MONTH) + (12 - cal.get(Calendar.MONTH));
                    }
                    if (diffMonth > -12 && diffMonth < 12) {
                        day = (diffMonth > 0) ? diffMonth + "月后" : Math.abs(diffMonth) + "月前";
                    }
                }
            } else {//差距大于一年
                day = getDateFormat().format(date).split(" ")[0];
            }
        }
//        if (day.contains(" ")) {
//            day = day.split(" ")[0];
//        }
        return day;
    }

    private static SimpleDateFormat getDateFormat() {
        if (null == DateLocal.get()) {
            DateLocal.set(new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA));
        }
        return DateLocal.get();
    }

//    public static String GetDateWithChinese(String mServerDate) {
//        if (StringUtil.isEmpty(mServerDate)) {
//            return null;
//        }
//        mServerDate = mServerDate.replace("/", "-");
//        try {
//            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINESE);
//            Date serverDate = df.parse(mServerDate);
//            Date currentDate = new Date(System.currentTimeMillis());
//            Calendar serverCalendar = Calendar.getInstance();
//            Calendar currentCalendar = Calendar.getInstance();
//            serverCalendar.setTime(serverDate);
//            currentCalendar.setTime(currentDate);
//
//            int serverYear = serverCalendar.get(Calendar.YEAR);
//            int serverMonth = serverCalendar.get(Calendar.MONTH);
//            int serverDay = serverCalendar.get(Calendar.DATE);
//
//            int currentYear = currentCalendar.get(Calendar.YEAR);
//            int currentMonth = currentCalendar.get(Calendar.MONTH);
//            int currentDay = currentCalendar.get(Calendar.DATE);
//
//            int hour = serverCalendar.get(Calendar.HOUR_OF_DAY);
//
//            int minute = serverCalendar.get(Calendar.MINUTE);
//            String hours = hour < 10 ? "0" + hour : hour + "";
//            String minutes = minute < 10 ? "0" + minute : minute + "";
//
//            if (serverYear == currentYear) {
//                mServerDate = (serverMonth + 1) + "月" + serverDay + "日 " + hours + ":" + minutes;
//                if (serverMonth == currentMonth) {
//                    if (serverDay == currentDay) {
//                        mServerDate = "今天 " + hours + ":" + minutes;
//                    } else if (serverDay - currentDay == 1) {
//                        mServerDate = "明天 " + hours + ":" + minutes;
//                    } else if (serverDay - currentDay == 2) {
//                        mServerDate = "后天 " + hours + ":" + minutes;
//                    } else if (serverDay - currentDay == -1) {
//                        mServerDate = "昨天 " + hours + ":" + minutes;
//                    } else if (serverDay - currentDay == -2) {
//                        mServerDate = "前天 " + hours + ":" + minutes;
//                    } else if (serverDay - currentDay > 0) {
//                        mServerDate = serverDay - currentDay + "天后";
//                    } else {
//                        mServerDate = currentDay - serverDay + "天前";
//                    }
//                } else if (currentMonth > serverMonth) {
//                    mServerDate = (currentMonth - serverMonth) + "月前";
//                }
//            } else if (currentYear > serverYear) {
//                mServerDate = (currentYear - serverYear) + "年前";
//            }
//
//            return mServerDate;
//        } catch (ParseException e) {
//            return null;
//        }
//    }

    /**
     * 根据固定格式返回时间戳
     *
     * @param timeString
     * @param formatType
     * @return
     */
    public static long getTimestampByTime(String timeString, String formatType) {
        SimpleDateFormat formatter = new SimpleDateFormat(formatType,
                Locale.CHINESE);
        try {
            Date d = formatter.parse(timeString);
            return d.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 判断时间戳是否在今一天
     *
     * @param timestamp
     * @return
     */
    public static boolean isToday(long timestamp) {
        String timeString = getFormatTimeByTimeMillis(timestamp, "yyyy-MM-dd");
        String todayString = getFormatTimeByTimeMillis(
                System.currentTimeMillis(), "yyyy-MM-dd");
        return timeString.equals(todayString);
    }

    /**
     * 获取本周星期一的日期
     *
     * @return
     */
    public static String getMondayOfWeek() {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());
        c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        return getFormatTimeByTimeMillis(c.getTimeInMillis(), "yyyy-MM-dd");
    }

    /**
     * 获取本月第一天的日期
     *
     * @return
     */
    public static String getFirstDayOfMonth() {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());
        c.set(Calendar.DAY_OF_MONTH, 1);
        return getFormatTimeByTimeMillis(c.getTimeInMillis(), "yyyy-MM-dd");
    }

    /**
     * 获取两个日期之间的间隔天数
     *
     * @return
     */
    public static int getGapCount(Date startDate, Date endDate) {
        Calendar fromCalendar = Calendar.getInstance();
        fromCalendar.setTime(startDate);
        fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
        fromCalendar.set(Calendar.MINUTE, 0);
        fromCalendar.set(Calendar.SECOND, 0);
        fromCalendar.set(Calendar.MILLISECOND, 0);

        Calendar toCalendar = Calendar.getInstance();
        toCalendar.setTime(endDate);
        toCalendar.set(Calendar.HOUR_OF_DAY, 0);
        toCalendar.set(Calendar.MINUTE, 0);
        toCalendar.set(Calendar.SECOND, 0);
        toCalendar.set(Calendar.MILLISECOND, 0);

        return (int) ((toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24));
    }

    //计算日期为当年的第几周
    public static Integer getWeekOfYear(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTime(date);
        int week = calendar.get(Calendar.WEEK_OF_YEAR);
        int mouth = calendar.get(Calendar.MONTH);
        // JDK think 2015-12-31 as 2016 1th week
        //如果月份是12月，且求出来的周数是第一周，说明该日期实质上是这一年的第53周，也是下一年的第一周
        if (mouth >= 11 && week <= 1) {
            week += 52;
        }
        return week;
    }

    //判断是否为闰年
    public static boolean isLeapYear(int year) {
        if (year <= 0) {
            return false;
        }

        return year % 4 == 0 && year % 100 != 0 || year % 400 != 0;
    }

    /**
     * 只有年月日
     */
    public static String getYMDTime(String mServerData) {
        if (StringUtil.isEmpty(mServerData)) {
            return null;
        }
        mServerData = mServerData.replace("/", "-");
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        try {
            mServerData = f.format(f.parse(mServerData));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return mServerData;
    }
}
